﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using studPage.Model;
using System.Windows.Threading;
using System.Windows.Data;
using System.Net.NetworkInformation;
using System.Xml;
using System.ServiceModel.Syndication;
using System.IO;

namespace studPage
{
    public partial class Search : Page
    {
        ObservableCollection<SearchRsBySchool> searchResults = new ObservableCollection<SearchRsBySchool>();
        PagedCollectionView pcv;
        DispatcherTimer _timer;
        private string _lastId = "0";
        private bool _gotLatest = false;
        public Search()
        {
            InitializeComponent();
            List<string> schoolname = new List<string>();
            schoolname.Add("信息科学与技术学院");
            schoolname.Add("管理学院");
            schoolname.Add("传播与设计学院");
            schoolname.Add("软件学院");
            schoolname.Add("岭南学院");
            SearchComboBox.ItemsSource = schoolname;
        }

        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        void OnNetworkChanged(object sender, EventArgs e)
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                // network may not be available, halt searching
                SearchButton.IsEnabled = false;
                SearchButton.Content = "DISCONNECTED";
                _timer.Stop();
            }
            else
            {
                SearchButton.Content = "SEARCH";
                SearchButton.IsEnabled = true;
                _timer.Start();
            }
        }

        void OnTimerTick(object sender, EventArgs e)
        {
            SearchForTweetsEx();
        }

        void Search_Loaded(object sender, RoutedEventArgs e)
        {
            SearchResults.ItemsSource = pcv; // bind the DataGrid
            _timer.Start(); // start the timer
            SearchForTweetsEx(); // do the initial search
            //SearchTerm.ItemsSource = Helper.GetSearchTermHistory(); // populate autocomplete
        }



        private void SearchForTweets(object sender, RoutedEventArgs e)
        {
            SearchForTweetsEx();
        }

        private void SearchForTweetsEx()
        {
            if (!string.IsNullOrEmpty(SearchComboBox.SelectedItem.ToString()))
            {
                _timer.Stop(); // stop the timer in case the search takes longer than the interval
                ActivityIndicator.IsActive = true; // set the visual indicator

                _lastId = Helper.GetLatestTeacherId(SearchComboBox.SelectedItem.ToString()); // get the latest ID from settings

                Helper.SaveLatestTeacherId(SearchComboBox.SelectedItem.ToString(), _lastId); // saving for history even if a result isn't found

                // do the work to search twitter and handle the completed event
                //WebClient proxy = new WebClient();
               // proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
               // proxy.OpenReadAsync(SearchComboBox.SelectedItem.ToString());
            }
        }

        void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            
            if (e.Error == null)
            {
                _gotLatest = false; // reset the latest detector
                string xmlStr = e.Result.ToString();
                using (XmlReader xReader = XmlReader.Create(new StringReader(xmlStr)))
                {
                    xReader.Read();
                    while (xReader.Read())
                    {
                        try
                        {
                            xReader.ReadToFollowing("Tid");
                            string _tid = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("Name");
                            string _name = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("Introduce");
                            string _introduce = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("link");
                            string _link = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("school");
                            string _school = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("tele");
                            string _tele = xReader.ReadElementContentAsString();
                            xReader.ReadToNextSibling("email");
                            string _email = xReader.ReadElementContentAsString();
                            SearchRsBySchool SearchRsBySchoolInfo = new SearchRsBySchool();
                            SearchRsBySchoolInfo.Tid = _tid;
                            SearchRsBySchoolInfo.Name = _name;
                            SearchRsBySchoolInfo.Introduce = _introduce;
                            SearchRsBySchoolInfo.link = _link;
                            SearchRsBySchoolInfo.school = _school;
                            SearchRsBySchoolInfo.tele = _tele;
                            SearchRsBySchoolInfo.email = _email;
                            searchResults.Add(SearchRsBySchoolInfo);
                        }
                        catch (Exception ex)
                        { }

                    }
                }

                Helper.SaveLatestTeacherId(SearchComboBox.SelectedItem.ToString(), _lastId); //saving last tweet id
            }
            else
            {
                // initialize our ErrorWindow with exception details
                ChildWindow errorWindow = new ErrorWindow(e.Error);
                errorWindow.Show();
            }
            ActivityIndicator.IsActive = false; // reset the UI
            _timer.Start(); // reset the timer
        }

        private string GetTweetId(string twitterId)
        {
            string[] parts = twitterId.Split(":".ToCharArray());
            if (!_gotLatest)
            {
                _lastId = parts[2].ToString();
            }
            return parts[2].ToString();
        }
    }
}